package com.ichina.chat.daoall;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class ObjectDaoimpl implements ObjectDao {

	@Resource
	private SessionFactory sessionFactory;
	private Session session;
	private Query query;

	public void del(Object arg0) {
		session = sessionFactory.getCurrentSession();
		session.delete(arg0);
	}

	public Object getAll(String hql) {
		session = sessionFactory.getCurrentSession();
		return session.createQuery(hql).list();
	}

	public int getAllCounte(String hql) {
		session = sessionFactory.getCurrentSession();
		return session.createQuery(hql).list().size();
	}

	public Object getHql(String hql) {
		session = sessionFactory.getCurrentSession();
		return session.createQuery(hql).uniqueResult();
	}

	public Object getHql(String hql, Object[] param) {
		session = sessionFactory.getCurrentSession();
		if (param != null) {
			query = session.createQuery(hql);
			for (int i = 0; i < param.length; i++) {
				query.setParameter(i, param[i]);
			}
			return query.list();
		}
		return null;
	}

	public Object getSql(String sql) {
		session = sessionFactory.getCurrentSession();
		return session.createSQLQuery(sql).list();
	}

	public Object getSql(String sql, Object[] param) {
		session = sessionFactory.getCurrentSession();
		if (param != null) {
			SQLQuery sqlQuery = session.createSQLQuery(sql);
			for (int i = 0; i < param.length; i++) {
				sqlQuery.setParameter(i, param[i]);
			}
			return sqlQuery.list();
		}
		return null;
	}

	public Object load(Class voClass, int id) {
		return sessionFactory.getCurrentSession().get(voClass, id);
	}

	public void saveOrUpdate(Object vo) {
		session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(vo);
	}

	public Object getAll(String hql, int cp, int pagesize) throws Exception {
		session = sessionFactory.getCurrentSession();
		return session.createQuery(hql)
				.setFirstResult(pagesize * cp - pagesize).setMaxResults(
						pagesize).list();
	}

	public void update(String sql) throws Exception {
		sessionFactory.getCurrentSession().createQuery(sql).executeUpdate();
	}

}
